﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTableToEntityClass
{
    /// <summary>
    /// MSSQL数据库表 批量转c#实体类 劳承杰 2019年1月3日15:30:51
    /// </summary>
    public class BLL
    {
        static IDAL _iDal = new DAL();
        public List<TempModel> GetDataBaseList(string conStr)
        {
            return _iDal.GetDataBaseList(conStr);
        }
        public List<TempModel> GetTableList(string conStr)
        {
            return _iDal.GetTableList(conStr);
        }

        /// <summary>
        /// 生成整个数据库 所有表
        /// </summary>
        /// <param name="conStr"></param>
        /// <param name="dataBase"></param>
        public void GenerateEntityClass(string conStr, string dataBase, string savePath)
        {
            var table = _iDal.GetTableList(conStr);
            Parallel.ForEach(table, (item) => { GenerateEntityClass(conStr, dataBase, savePath, item.Name); });
        }

        /// <summary>
        /// 生成指定表
        /// </summary>
        /// <param name="conStr"></param>
        /// <param name="dataBase"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public bool GenerateEntityClass(string conStr, string dataBase,string savePath, string table)
        {
            var col = _iDal.GetTableColumns(conStr, table);
            if (col.Count == 0)
            {
                return false;
            }
            StringBuilder strEntity = new StringBuilder(1000);
            strEntity.Append("using System;\r\n");
            strEntity.Append("using System.Collections.Generic;\r\n");
            strEntity.Append("using System.Linq;\r\n");
            strEntity.Append("using System.Text;\r\n");
            strEntity.Append("\r\n");
            strEntity.Append($"namespace {dataBase}\r\n");
            strEntity.Append("{\r\n");
            strEntity.Append($"\tpublic class {table}\r\n");
            strEntity.Append("\t{\r\n");
            foreach (var item in col)
            {
                if (!string.IsNullOrWhiteSpace(item.Description))
                {
                    strEntity.Append("\t\t/// <summary>\r\n");
                    strEntity.Append($"\t\t///{item.Description}\r\n");
                    strEntity.Append("\t\t/// </summary>\r\n");
                }
                strEntity.Append($"\t\tpublic {dbTypeToCsharpType(item.Type)} {item.Name} {{ get; set; }}\r\n");
            }
            strEntity.Append("\t}\r\n");
            strEntity.Append("}");

            var folder= $"{(savePath!=string.Empty?savePath:AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\'))}\\{dataBase}";
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var fileUrl = $"{folder}/{table}.cs";
            using (FileStream fs = new FileStream(fileUrl, FileMode.Create))
            {
                var b = Encoding.UTF8.GetBytes(strEntity.ToString());
                fs.Write(b, 0, b.Length);
                fs.Close();
            }
            return true;
        }
        string dbTypeToCsharpType(string dbType)
        {
            string cSharpType=string.Empty;
            switch (dbType)
            {
                case "bit":
                    cSharpType = "bool";
                    break;
                case "text":
                case "ntext":
                case "char":
                case "nchar":
                case "nvarchar":
                case "varchar":
                    cSharpType = "string";
                    break;
                case "int":
                    cSharpType = "int";
                    break;
                case "bigint":
                    cSharpType = "Int64";
                    break;
                case "smallint":
                    cSharpType = "Int16";
                    break;
                case "decimal":
                case "money":
                case "numeric":
                case "smallmoney":
                    cSharpType = "decimal";
                    break;
                case "float":
                    cSharpType = "double";
                    break;
                case "datetime":
                case "smalldatetime":
                case "timestamp":
                    cSharpType = "DateTime";
                    break;
                case "binary":
                case "image":
                case "varbinary":
                    cSharpType = "byte[]";
                    break;
                case "tinyint":
                    cSharpType = "byte";
                    break;
                case "real":
                    cSharpType = "Single";
                    break;
                case "uniqueidentifier":
                    cSharpType = "Guid";
                    break;
                case "Variant":
                    cSharpType = "object";
                    break;
                default:
                    cSharpType = "string";
                    break;
            }
            return cSharpType;
        }
        /// <summary>
        /// Windows身份验证方式的数据库连接
        /// </summary>
        /// <param name="dataBase"></param>
        /// <param name="serverAddress"></param>
        /// <returns></returns>
        public string GetConn(string dataBase,string serverAddress)
        {
            return $"Data Source={serverAddress};Initial Catalog={dataBase};Integrated Security=SSPI;";
        }
        /// <summary>
        /// SQL Server身份验证方式的数据库连接
        /// </summary>
        /// <param name="dataBase"></param>
        /// <param name="serverAddress"></param>
        /// <param name="userID"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string GetConn(string dataBase, string serverAddress,string userID,string password)
        {
            return $"Data Source={serverAddress};Initial Catalog={dataBase};User ID={userID};Password={password};";
        }
    }
}
